#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>

using namespace std;

//回调函数
void myMouseCallback(int event, int x, int y, int flags, void* param);

cv::Rect box;
bool drawingBox = false;

void drawBox(cv::Mat& img, cv::Rect box)
{
    cv::rectangle(
                img,
                box.tl(),
                box.br(),
                cv::Scalar(0xff, 0x00, 0x00)
                );
}

void help()
{
    cout << "Call: ./ch4.exe_1\n" <<  "show how to use a mouse to "
                                      "draw regions in an image." << endl;
}

int main()
{
    help();
    box = cv::Rect(-1, -1, 0, 0);
    //cv::Mat image(200, 200, CV_8UC3), temp;
    cv::Mat image, temp;
    image = cv::imread("../../resource/image/lenna.jpg", -1);
    image.copyTo(temp);

    box = cv::Rect(-1, -1, 0, 0);
    //image = cv::Scalar::all(0);
    cv::namedWindow("Box Example", cv::WINDOW_AUTOSIZE);

    cv::setMouseCallback(
                "Box Example",
                myMouseCallback,
                (void*)& image);

    for (;;)
    {
        /*
         * 1. 连续刷新, temp每次重载为EVENT_LBUTTONUP未发生时的image图像
         * 2. 然后temp根据EVENT_MOUSEMOVE图像显示box
         * 3. 返回第一步
        */
        image.copyTo(temp);
        if (drawingBox)
            drawBox(temp, box);
        cv::imshow("Box Example", temp);

        if (cv::waitKey(15) == 27)
            break;
    }

    return 0;
}

void myMouseCallback(int event, int x, int y, int flags, void* param)
{
    cv::Mat& image = *(cv::Mat*)param;
    switch (event)
    {
        case cv::EVENT_MOUSEMOVE:
        {
            cout << "Mouse moving" << endl;
            if (drawingBox)
            {
                box.width = x-box.x;
                box.height = y-box.y;
            }
            break;
        }
        case cv::EVENT_LBUTTONDOWN:     //只会执行一次
        {
            cout << "Left button down" << endl;
            drawingBox = true;
            box = cv::Rect(x, y, 0, 0);
            break;
        }
        case cv::EVENT_LBUTTONUP:
        {
            cout << "Left button up" << endl;
            drawingBox = false;
            if (box.width < 0)
            {
                box.x += box.width;
                box.width *= -1;
            }
            if (box.height < 0)
            {
                box.y += box.height;
                box.height *= -1;
            }
            drawBox(image, box);
            break;
        }
    }
}
